package com.example.gitproject.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.example.gitproject.Entity.Result;
import com.example.gitproject.Entity.User;
import com.example.gitproject.Entity.vo.LoginVo;
import com.example.gitproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("ser")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {

        if (userService.login(loginVo) == true) {
            //会话登录:参数填写要登录的账号id
            //此时传入的id 就是当前登录账号的id
            User user = userService.getUserAll(loginVo);
            if (user!=null) {
                StpUtil.login(user.getId());
            }

            return new Result(true, "登录成功");
        } else {
            return new Result(false, "登录失败,账号或密码错误");
        }
    }



    @PostMapping("/login2")
    public SaResult login2(@RequestBody LoginVo loginVo) {

        if (userService.login(loginVo) == true) {
            User user = userService.getUserAll(loginVo);
            if (user!=null) {
                StpUtil.login(user.getId());
            }

            return SaResult.ok("登录成功");
        } else {
            return SaResult.error("登录失败,账号或密码错误");
        }
    }



    // 查询登录状态  ---- http://localhost:8082/ser/isLogin
    @GetMapping("isLogin")
     public SaResult isLogin() {
            return SaResult.ok("是否登录：" + StpUtil.isLogin());
        }

    // 查询 Token 信息  ---- http://localhost:8082/ser/tokenInfo
    @GetMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    // 测试注销  ---- http://localhost:8082/api/test/logout
    @PostMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }



}
